import React, { useState, useEffect } from 'react';
import reactCSS from 'reactcss'
import { SketchPicker } from 'react-color'


// props.color {r:255,g:255,b:255,a:255,lbl:'color',val:9999}
// props.onChange
function ColorSwath(props) {
    
    const [currColor, setCurrColor] = useState({r:255,g:255,b:255,a:0.5}) ;
    const [currColorStr, setCurrColorStr] = useState("rgba(255,255,255,1.0)");
    const [show, setShow] = useState(false);

    //color1.r g b a should be 0-255
    //output str should be rgba(255,255,255,1.0)
    const convertColorObj2CssRGBAStr = function(color1){
        return "rgba("+color1.r+","+color1.g+","+color1.b+","+(color1.a/255.0).toFixed(2)+")" ;
    }

    useEffect(() => {
        let newColor = {};
        newColor.r = props.color.r ;
        newColor.g = props.color.g ;
        newColor.b = props.color.b ;
        newColor.a = parseFloat((props.color.a/255.0).toFixed(2)) ;
        console.log(newColor);
        setCurrColor(newColor) ;
        setCurrColorStr( convertColorObj2CssRGBAStr(props.color) );
    }, [props.color])
    
    const onCloseColorPicker = function() {
        setShow(false);
    }

    const onColorChanged=function (color, event) {
        let newColor = {... props.color} ;
        newColor.r = color.rgb.r ;
        newColor.g = color.rgb.g ;
        newColor.b = color.rgb.b ;
        newColor.a = parseInt( color.rgb.a * 255 ) ;
        setCurrColor(color.rgb) ;
        setCurrColorStr( convertColorObj2CssRGBAStr(newColor)) ;
        props.onChange(newColor) ;
    }

    const onShowColorPicker = function() {
        setShow(true);
    }

    return (
        <>
        <div 
        style={{position:'relative', cursor:'pointer',width:'22px',height:'22px',border:'1px solid #aaa',backgroundColor:'white',padding:'2px'}}
        onClick={onShowColorPicker}
        >
            <div style={{
                width:'16px',height:'16px',
                inset: '0px',
                background: "url('') left center"
                }}
            >
            </div>
            <div 
            style={{ position:'absolute',top:'2px',left:'2px', width:'16px',height:'16px',border:'1px solid #aaa',backgroundColor:currColorStr}}
            >
            </div>
        </div>
        {
                        
            (show) ? (
                <div style={{ position: 'absolute', zIndex: '2' }}>
                    <div
                        onClick={onCloseColorPicker}
                        style={{ position: 'fixed', top: '0px', right: '0px', bottom: '0px', left: '0px', }} >
                    </div>
                    <SketchPicker 
                    color={ currColor }
                    onChange={onColorChanged} />
                </div>
            ) : null
        }
        </>
    )
}

export default ColorSwath